<?php

namespace app\admin\controller\finance;

use addons\shopro\model\UserWalletLog;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;


/**
 * 热销商品
 *
 * @icon fa fa-circle-o
 */
class Goodshot extends Backend
{
    /**
     * Activity模型对象
     * @var \app\admin\model\shopro\activity\Retailorder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();

            }
            $filter = $this->request->get("filter");
            $filter = (array)json_decode($filter, true);

            $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
            $order = $this->request->get("order", "DESC");
            $offset = $this->request->get("offset", 0);
            $limit = $this->request->get("limit", 0);

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $datestr = "所有";
            if(isset($filter['date'])){
                $where = [];
                $rawdate = $filter['date'];
                $rawdate = str_replace(' - ', ',', $rawdate);
                $arr = array_slice(explode(',', $rawdate), 0, 2);

                $where['item.createtime'][] = ['gt',strtotime($arr[0])];
                $where['item.createtime'][] = ['lt',strtotime($arr[1])];

                $datestr = date("Y-m-d",strtotime($arr[0])) . "~" . date("Y-m-d",strtotime($arr[1]));
            }

            $list = db('shopro_order_item')
                ->alias('item')
                ->fieldRaw("'{$datestr}' as date,sum(item.cost_price) as cost_cnt,sum(item.commission) as commission_cnt,sum(item.goods_price) as price_cnt,sum(item.goods_num) as sum_num,item.goods_id, item.goods_title,count(1) as cnt")
                ->join('shopro_order o','o.id = item.order_id')
                ->where(['o.status'=>['gt',0]])
                ->where($where)
                ->order("cnt desc")
                ->group("item.goods_id")
                ->paginate($limit);

            $retdata = $list->items();
            foreach ($retdata as &$item){
                $item['profit'] = round($item['price_cnt'] - $item['cost_cnt'] - $item['commission_cnt'],2);
            }

            $totaldata = $this->total($retdata);
            if(!empty($totaldata)){
                //不为空
                $retdata[] = $totaldata;
            }

            $result = array("total" => $list->total(), "rows" => $retdata);

            return json($result);
        }
        return $this->view->fetch();
    }

    protected function total($retdata)
    {
        //汇总
        $totaldata = [];
        if(!empty($retdata[0])){
            foreach ($retdata[0] as $k=>$v){
                if($k=='date'){
                    $totaldata[$k] = '汇总';
                }else{
                    $totaldata[$k] = 0;
                }
            }
        }

        foreach ($retdata as $item) {
            $totaldata['cnt'] = round($totaldata['cnt'] + $item['cnt'], 2);
            $totaldata['sum_num'] = round($totaldata['sum_num'] + $item['sum_num'], 2);
            $totaldata['price_cnt'] = round($totaldata['price_cnt'] + $item['price_cnt'], 2);
            $totaldata['cost_cnt'] = round($totaldata['cost_cnt'] + $item['cost_cnt'], 2);
            $totaldata['commission_cnt'] = round($totaldata['commission_cnt'] + $item['commission_cnt'], 2);
            $totaldata['profit'] = round($totaldata['profit'] + $item['profit'], 2);
        }

        return $totaldata;
    }

}
